﻿Imports System.Data

Public Class Cart
    Inherits CoreClass

    Dim objDT As System.Data.DataTable
    Dim objDR As System.Data.DataRow

    Public Sub makeCart()
        objDT = New System.Data.DataTable("Cart")
        objDT.Columns.Add("IdCart", GetType(Integer))
        objDT.Columns("IdCart").AutoIncrement = True
        objDT.Columns("IdCart").AutoIncrementSeed = 1
        objDT.Columns.Add("ProId", GetType(String))
        objDT.Columns.Add("ProImg", GetType(String))
        objDT.Columns.Add("ProName", GetType(String))
        objDT.Columns.Add("Quantity", GetType(Integer))
        objDT.Columns.Add("ProPrice", GetType(Double))
        objDT.Columns.Add("Total", GetType(Double))
        Session("Cart") = objDT
    End Sub

    Public Sub AddToCart(ByVal id As String, ByVal name As String, ByVal img As String, ByVal quantity As Integer, ByVal price As Double)
        objDT = Session("Cart")
        Dim total As Double = 0
        ' Bien kiem tra xem da co san pham nay hay chua, FALSE la chua co san pham nay trong gio hang
        Dim blnMatch As Boolean = False
        ' Chay tuong row trong table
        For Each objDR In objDT.Rows
            ' Neu co roi thi update so luong
            If objDR("ProId") = id Then
                objDR("Quantity") += quantity
                ' Lay lai bien so luong tai thoi diem hien tai de update tong gia tien
                Dim currQuantity As Integer = Integer.Parse(objDR("Quantity").ToString)
                total = price * currQuantity
                objDR("Total") = total
                blnMatch = True
                Exit For
            End If
        Next
        ' Neu chua co san pham
        If Not blnMatch Then
            objDR = objDT.NewRow
            objDR("ProId") = id
            objDR("ProImg") = img
            objDR("ProName") = name
            objDR("Quantity") = quantity
            objDR("ProPrice") = price
            total = price * quantity
            objDR("Total") = total
            ' them row moi vao table
            objDT.Rows.Add(objDR)
        End If
        ' Add lai session
        Session("Cart") = objDT
    End Sub
End Class


